package com.solution.common.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.util.Base64;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.ibatis.common.beans.Probe;
import com.ibatis.common.beans.ProbeFactory;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.common.config.PublicConfig;
import com.solution.common.config.PublicConfigUtil;
import com.solution.common.entity.UserPrincipal;
import com.solution.common.exception.BizException;
import com.solution.common.exception.WebException;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;

/**
 * 控制层基类
 * @author llp
 * @date 2017/4/8
 */
public class BaseController {
	protected static Probe probe = ProbeFactory.getProbe();
	@SuppressWarnings("unused")
	private Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	private static final String SUCCESS_CODE = "1";
	private static final String FAILED_CODE = "1";
	private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS";
	private static final String DEFAULT_FAILED_FAILED = "FAILED";
	
	
	
	/**
	 * 返回异步成功消息
	 * @param resultMap
	 * @param result
	 * @param msg
	 */
	public void syncSuccessReslt(Map<String, String> resultMap ,int result, String msg){
		if(result > 0){
			resultMap.put("resultCode", SUCCESS_CODE);
			resultMap.put("resultMsg", StringUtil.isNotEmpty(msg) ? msg : DEFAULT_SUCCESS_MESSAGE);
		}else{
			resultMap.put("resultCode", FAILED_CODE);
			resultMap.put("resultMsg", StringUtil.isNotEmpty(msg) ? msg : DEFAULT_FAILED_FAILED);
		}
	}
	
	/**
	 * 返回异步成功消息
	 * @param resultMap
	 * @param result
	 * @param msg
	 */
	public void syncSuccessReslt(Map<String, String> resultMap ,int result){
		if(result > 0){
			resultMap.put("resultCode", SUCCESS_CODE);
			resultMap.put("resultMsg", DEFAULT_SUCCESS_MESSAGE);
		}else{
			resultMap.put("resultCode", FAILED_CODE);
			resultMap.put("resultMsg", DEFAULT_FAILED_FAILED);
		}
	}
	
	/**
	 * 返回异步错误消息
	 * @param resultMap
	 * @param result
	 * @param msg
	 */
	public void syncErrorReslt(Map<String, String> resultMap){
		resultMap.put("resultCode", FAILED_CODE);
		resultMap.put("resultMsg", DEFAULT_FAILED_FAILED);
	}

	/**
	 * 将datList 中的数据写入到Excel
	 * @param headNames excel字段要显示的名字
	 * @param fieldNames datList 元素类对应实体的属性
	 * @param datList  要导出的excel的数据元素可以是任意类，该类的类型保存在数据库相关配置明细
	 * @fileName 导出文件名称
	 * @param os  浏览器Response 的输出流
	 */
	@SuppressWarnings({ "rawtypes" })
	protected void expToExcel07(HttpServletRequest request, HttpServletResponse response, List<String> headNames, List<String> fieldNames,
	        String fileName, List datList) {
		try {
			response.setContentType("application/vnd.ms-excel");
			String agent = (String) request.getHeader("USER-AGENT");
			if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
				String downloadFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
				response.setHeader("Content-disposition", "attachment;filename=" + downloadFileName);
			} else {
				response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
			}
			// 判断参数异步情况
			if (headNames == null || headNames.isEmpty()) {
				return;
			}
			if (fieldNames == null || fieldNames.isEmpty()) {
				return;
			}
			if (datList == null) {
				datList = Collections.EMPTY_LIST;
			}
			// 创建文件
			XSSFWorkbook wb = new XSSFWorkbook();
			XSSFSheet sheet = wb.createSheet(fileName.substring(0, fileName.indexOf(".")));
			if (headNames != null && !headNames.isEmpty()) {
				int minWidth = 3072;
				// 先制作表头
				Row row = sheet.createRow(0);
				for (int i = 0; i < headNames.size(); i++) {
					String title = headNames.get(i);
					int columnWidth = title.getBytes().length * 512;
					sheet.setColumnWidth(i, (columnWidth > minWidth ? columnWidth : minWidth));
					row.createCell(headNames.indexOf(title)).setCellValue(title);
				}
			}
			// 将数据据行写入excel
			for (Object dat : datList) {
				Row row = sheet.createRow(datList.indexOf(dat) + 1);
				for (String field : fieldNames) {
					Object value = probe.getObject(dat, field);
					String valueStr = "";
					if (value != null) {
						valueStr = value.toString();
					}
					row.createCell(fieldNames.indexOf(field)).setCellValue(valueStr);
				}
			}
			// 返回请求的注，直接在浏览器中弹出窗口下载excel
			wb.write(response.getOutputStream());
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取当前登录用户对象
	 * 
	 * @return 当前用户
	 * @author llp
	 * @date 2017/4/19 2:16
	 */
	protected UserPrincipal getCurrentUser() {
		Subject currentUser = SecurityUtils.getSubject();
		return (UserPrincipal) currentUser.getPrincipal();
	}

	/**
	 * 获取经销商ID
	 * 
	 * @return
	 */
	protected Long getDealerId() {
		Subject currentUser = SecurityUtils.getSubject();
		UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
		return user.getDealerId();
	}
	
	/**
	 * 获取用户权限数据标识 
	 * @return
	 */
	protected String getUserAuthType(){
		Subject currentUser = SecurityUtils.getSubject();
		UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
		return user.getUserAuthType();
	}

	/**
	 * 获取经销商名称
	 * 
	 * @return
	 */
	protected String getDealerName() {
		Subject currentUser = SecurityUtils.getSubject();
		UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
		return user.getDealerName();
	}

	/**
	 * 获取用户类型
	 * 
	 * @return
	 */
	protected Integer getUserType() {
		Subject currentUser = SecurityUtils.getSubject();
		UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
		return user.getUserType();
	}

	/**
	 * 客户当前客户级别
	 * 
	 * @return
	 */
	protected String getCustomerLevel() {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
			if (user != null && user.getCompany() != null) {
				return String.valueOf(user.getCompany().getCustomerLevel());
			} else {
				// 后台人员登录系统，看游客价格
				return PublicConfigUtil.readConfig("tourist.customer.level");
			}
		} else {
			// 匿名客户默认级别为0，显示游客价
			return PublicConfigUtil.readConfig("tourist.customer.level");
		}
	}

	/**
	 * 客户支付模式 字典字义：01 立即支付 02 货到付款 页面显示逻辑：01 - 显示立即支付 02-显示
	 * 
	 * @return
	 */
	protected String getCustomerPayModel() {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
			if (user != null && user.getCompany() != null) {
				String allowedPayModel = user.getCompany().getAllowedPayType();
				if (StringUtil.isNotEmpty(allowedPayModel)) {
					return allowedPayModel;
				}else{
					return "01";
				}
			} else {
				return "01";
			}
		} else {
			return "01";
		}
	}

	/**
	 * 获取当前客户ID
	 * 
	 * @return
	 */
	protected long getCustomerId() {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
			if (user != null && user.getCustomer() != null) {
				return user.getCustomer().getId();
			} else {
				throw new BizException("无法获取当前客户ID");
			}
		}
		return 0;
	}

	/**
	 * 获取当前客户ID
	 * 
	 * @return
	 */
	protected long getCompanyId() {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
			if (user != null && user.getCompany() != null) {
				return user.getCompany().getId();
			} else {
				throw new BizException("无法获取当前客户公司ID");
			}
		}
		return 0;
	}

	/**
	 * 获取当前客户单位
	 * 
	 * @return
	 */
	protected CompanyEntity getCompany() {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
			if (user != null && user.getCompany() != null) {
				return user.getCompany();
			} else {
				throw new BizException("无法当前客户公司");
			}
		}
		return null;
	}

	/**
	 * 获取当前客户
	 * 
	 * @return
	 */
	protected CustomerEntity getCustomer() {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
			if (user != null && user.getCustomer() != null) {
				return user.getCustomer();
			} else {
				throw new BizException("无法当前客户");
			}
		}
		return null;
	}

	/**
	 * 获取当前用户名(当前用户名为空时，使用session id 后20位当作用户id)
	 * 
	 * @param request
	 * @return
	 */
	protected String getCurrentUserCodeWithAnonymous(HttpServletRequest request) {
		String userCode = null;
		Subject subject = getSubject();
		if (subject.isAuthenticated()) {
			userCode = getUserCode();
		} else {
			userCode = request.getSession().getId().replace("-", "").substring(12);
		}
		return userCode;
	}

	/**
	 * 是否登录
	 * 
	 * @param request
	 * @return
	 */
	protected boolean isLogin(HttpServletRequest request) {
		boolean loginFlag = getSubject().isAuthenticated();
		if(loginFlag){
			Integer approveStatus = getCustomer().getStatus();
			// 待审核
			if(approveStatus == 0){
				return false;
			}else{
				return true;
			}
		}else{
			return false;
		}
	}

	/**
	 * 供controller 类分页前准备分页参数(defaultPageSize=默认每页个数)
	 * 
	 * @param request
	 * @param defaultPageSize
	 * @return PageParam
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年12月4日 下午4:45:35
	 */
	protected PageParam getPageParam(HttpServletRequest request, int defaultPageSize) {
		// 当前页码
		String tmpCurrentPage = request.getParameter("tmpCurrentPage");
		// 每页多少行
		String tmpNumPerPage = request.getParameter("tmpNumPerPage");
		int curPageNum = (tmpCurrentPage == null || "".equals(tmpCurrentPage.trim())) ? 1 : Integer.valueOf(tmpCurrentPage);
		int numPerPage = (tmpNumPerPage == null || "".equals(tmpNumPerPage.trim())) ? defaultPageSize : Integer.valueOf(tmpNumPerPage);
		// 分页参数
		PageParam param = new PageParam(curPageNum, numPerPage);
		return param;
	}

	/**
	 * 供controller 类分页前准备分页参数
	 * 
	 * @param request
	 * @return
	 */
	protected PageParam getPageParam(HttpServletRequest request) {
		// 当前页码
		String tmpCurrentPage = request.getParameter("tmpCurrentPage");
		// 每页多少行
		String tmpNumPerPage = request.getParameter("tmpNumPerPage");
		int curPageNum = (tmpCurrentPage == null || "".equals(tmpCurrentPage.trim())) ? 1 : Integer.valueOf(tmpCurrentPage);
		int numPerPage = (tmpNumPerPage == null || "".equals(tmpNumPerPage.trim())) ? 10 : Integer.valueOf(tmpNumPerPage);
		// 分页参数
		PageParam param = new PageParam(curPageNum, numPerPage);
		return param;
	}

	/**
	 * 获取用户认证主体
	 * 
	 * @return
	 */
	protected Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	/**
	 * 获取当前登录用户账号
	 * 
	 * @return 登录账号
	 * @author llp
	 * @date 2017/4/19 2:16
	 */
	protected String getUserCode() {
		Subject currentUser = SecurityUtils.getSubject();
		UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
		return user.getUserCode();
	}

	/**
	 * 获取当前登录用户ID
	 * 
	 * @return 用户ID
	 * @author llp
	 * @date 2017/4/19 2:16
	 */
	protected Long getUserId() {
		Subject currentUser = SecurityUtils.getSubject();
		UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
		return user.getId();
	}

	/**
	 * 获取当前登录用户姓名
	 * 
	 * @return 用户姓名
	 * @author llp
	 * @date 2017/4/19 2:16
	 */
	protected String getUserName() {
		Subject currentUser = SecurityUtils.getSubject();
		UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
		return user.getUserName();
	}

	/**
	 * 异常处理方法
	 * 
	 * @param message
	 * @param logger
	 * @param e
	 */
	public void handleException(String message, Logger logger, Exception e) {
		e.printStackTrace();
		logger.error("{}message，{}", "", e);
		throw new WebException(message, e);
	}

	/**
	 * 将一个上传的Excel解析到一个List
	 * 
	 * @param headNames
	 *            excel字段要显示的名字
	 * @param fieldNames
	 *            datList 元素类对应实体的属性
	 * @param eipId
	 *            导入配置ID
	 * @param fis
	 *            上传Response 请求的输入流
	 * @param hasTitle
	 *            导入文件是否有标题行
	 * @return hasTitle 上传excel是否有标识
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List impFromExcel07(MultipartHttpServletRequest request, List<String> headNames, List<String> fieldNames, String className,
	        boolean hasTitle) {
		List dataList = new ArrayList();
		List<MultipartFile> upload = request.getFiles("file");
		try {
			InputStream ins = upload.get(0).getInputStream();
			// 判断参数是否正确
			Workbook wb = WorkbookFactory.create(ins);
			// 解析单sheet文档
			Sheet sheet = wb.getSheetAt(0);
			// 行数
			int rowNum = sheet.getLastRowNum();
			// 如果有标题第1行不读
			int i = hasTitle ? 1 : 0;
			for (; i < rowNum; i++) {
				Class am = Class.forName(className);
				Object bean = am.newInstance();
				Row row = sheet.getRow(i);
				for (String field : fieldNames) {
					Object tmpVal = row.getCell(fieldNames.indexOf(field));
					if (tmpVal == null || "".equals(tmpVal.toString().trim())) {
						probe.setObject(bean, field, "");
					} else {
						probe.setObject(bean, field, tmpVal.toString().trim());
					}
				}
				dataList.add(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dataList;
	}

	@SuppressWarnings({ "rawtypes" })
	protected void expToNewExcel(HttpServletRequest request, HttpServletResponse response, String titleNames, List<String> headNames,
	        List<String> fieldNames, String fileName, List datList, String sheetFileName, String titleNames2, List<String> headNames2,
	        List<String> fieldNames2, String fileName2, List datList2) {
		try {
			response.setContentType("application/vnd.ms-excel");
			String agent = (String) request.getHeader("USER-AGENT");
			if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
				String downloadFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
				response.setHeader("Content-disposition", "attachment;filename=" + downloadFileName);
			} else {
				response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
			}
			// 判断参数异步情况
			if (headNames == null || headNames.isEmpty()) {
				return;
			}
			if (fieldNames == null || fieldNames.isEmpty()) {
				return;
			}
			if (datList == null) {
				datList = Collections.EMPTY_LIST;
			}
			// 创建文件
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet(sheetFileName);
			HSSFCellStyle cellStyle = wb.createCellStyle();
			// 合并单元格
			Row newrow = sheet.createRow(0);
			// Cell cell = newrow.createCell(0);
			HSSFCell cell = (HSSFCell) newrow.createCell(0);
			cellStyle.setWrapText(true);// 先设置为自动换行
			cell.setCellStyle(cellStyle);
			cell.setCellValue(new HSSFRichTextString(titleNames));
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));

			// 设置行高
			newrow.setHeight((short) 1000);

			if (headNames != null && !headNames.isEmpty()) {
				// 先制作表头
				Row row = sheet.createRow(1);
				for (int i = 0; i < headNames.size(); i++) {
					String title = headNames.get(i);
					sheet.setColumnWidth(i, title.getBytes().length * 2 * 256);
					row.createCell(headNames.indexOf(title)).setCellValue(title);
				}
			}

			// 将数据据行写入excel
			for (Object dat : datList) {
				Row row = sheet.createRow(datList.indexOf(dat) + 2);
				for (String field : fieldNames) {
					Object value = probe.getObject(dat, field);
					String valueStr = "";
					if (value != null) {
						valueStr = value.toString();
					}

					row.createCell(fieldNames.indexOf(field)).setCellValue(valueStr);
				}
			}

			// 创建第二个sheet
			HSSFSheet sheet2 = wb.createSheet(fileName2);
			sheet2.setAutobreaks(true);
			if (headNames2 != null && !headNames2.isEmpty()) {
				// 先制作表头
				Row row2 = sheet2.createRow(0);
				for (int i = 0; i < headNames2.size(); i++) {
					String title2 = headNames2.get(i);
					sheet2.setColumnWidth(i, title2.getBytes().length * 2 * 256);
					row2.createCell(headNames2.indexOf(title2)).setCellValue(title2);
				}
			}
			// 将数据据行写入excel
			for (int i = 0; i < datList2.size(); i++) {
				Object dat2 = datList2.get(i);
				HSSFRow row2 = sheet2.createRow(datList2.indexOf(dat2) + 1);
				row2.setHeight((short) 3000);
				for (int j = 0; j < fieldNames2.size(); j++) {
					String field2 = fieldNames2.get(j);
					if (field2.equals("voucherImagePath")) {
						Object value2 = probe.getObject(dat2, field2);
						String[] img = value2.toString().split("##");
						for (int k = 0; k < img.length; k++) {
							if (k != 0) {
								sheet2.setColumnWidth((fieldNames2.size() - 1) + k,
								        headNames2.get(fieldNames2.size() - 1).getBytes().length * 2 * 256);
							}
							ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
							// 获取图片流
							URL url = new URL(PublicConfig.IMG_ROOT_URL + img[k]);
							HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
							httpUrl.connect();
							BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream());
							BufferedImage bufferImg = ImageIO.read(bis);
							ImageIO.write(bufferImg, "png", byteArrayOut);
							// 画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
							HSSFPatriarch patriarch = sheet2.createDrawingPatriarch();
							// anchor主要用于设置图片的属性
							HSSFClientAnchor anchor = new HSSFClientAnchor(10, 0, 1023, 255, (short) ((fieldNames2.size() - 1) + k), (i + 1),
							        (short) ((fieldNames2.size() - 1) + k), (i + 1));
							anchor.setAnchorType(0);
							// 插入图片
							patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
						}
					} else {
						Object value2 = probe.getObject(dat2, field2);
						String valueStr2 = "";
						if (value2 != null) {
							valueStr2 = value2.toString();
						}
						row2.createCell(fieldNames2.indexOf(field2)).setCellValue(valueStr2);
					}
				}
			}
			// 返回请求的注，直接在浏览器中弹出窗口下载excel
			wb.write(response.getOutputStream());
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将datList 中的数据写入到Excel
	 * 
	 * @param headNames
	 *            excel字段要显示的名字
	 * @param fieldNames
	 *            datList 元素类对应实体的属性
	 * @param datList
	 *            要导出的excel的数据元素可以是任意类，该类的类型保存在数据库相关配置明细
	 * @fileName 导出文件名称
	 * @param os
	 *            浏览器Response 的输出流
	 */
	protected void expToExcel07(HttpServletRequest request, HttpServletResponse response, List<String> headNames, List<String> fieldNames,
	        List<Object> datList, String fileName) {
		try {
			response.setContentType("application/vnd.ms-excel");
			String agent = (String) request.getHeader("USER-AGENT");
			if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
				String downloadFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
				response.setHeader("Content-disposition", "attachment;filename=" + downloadFileName);
			} else {
				response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
			}
			// 判断参数异步情况
			if (headNames == null || headNames.isEmpty()) {
				return;
			}
			if (fieldNames == null || fieldNames.isEmpty()) {
				return;
			}
			if (datList == null) {
				datList = Collections.EMPTY_LIST;
			}
			// 创建文件
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet("DATA");
			HSSFCellStyle cellStyle = wb.createCellStyle();
			// 合并单元格
			Row newrow = sheet.createRow(0);
			// Cell cell = newrow.createCell(0);
			HSSFCell cell = (HSSFCell) newrow.createCell(0);
			cellStyle.setWrapText(true);// 先设置为自动换行
			cell.setCellStyle(cellStyle);
			cell.setCellValue(new HSSFRichTextString("导出标题"));
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));

			// 设置行高
			newrow.setHeight((short) 1000);

			if (headNames != null && !headNames.isEmpty()) {
				// 先制作表头
				Row row = sheet.createRow(1);
				for (int i = 0; i < headNames.size(); i++) {
					String title = headNames.get(i);
					sheet.setColumnWidth(i, title.getBytes().length * 2 * 256);
					row.createCell(headNames.indexOf(title)).setCellValue(title);
				}
			}

			// 将数据据行写入excel
			for (Object dat : datList) {
				Row row = sheet.createRow(datList.indexOf(dat) + 2);
				for (String field : fieldNames) {
					Object value = probe.getObject(dat, field);
					String valueStr = "";
					if (value != null) {
						valueStr = value.toString();
					}

					row.createCell(fieldNames.indexOf(field)).setCellValue(valueStr);
				}
			}
			// 返回请求的注，直接在浏览器中弹出窗口下载excel
			wb.write(response.getOutputStream());
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 晋塘塘 2017-05-25-11:17 将datList 中的数据写入到Excel
	 * 
	 * @param headNames
	 *            excel字段要显示的名字
	 * @param fieldNames
	 *            datList 元素类对应实体的属性
	 * @param datList
	 *            要导出的excel的数据元素可以是任意类，该类的类型保存在数据库相关配置明细
	 * @fileName 导出文件名称
	 * @param os
	 *            浏览器Response 的输出流
	 */
	@SuppressWarnings({ "rawtypes" })
	protected void expToNewExcelNoSecondSheet(HttpServletRequest request, HttpServletResponse response, String titleNames, List<String> headNames,
	        List<String> fieldNames, String fileName, List datList, String sheetFileName) {
		try {
			response.setContentType("application/vnd.ms-excel");
			String agent = (String) request.getHeader("USER-AGENT");
			if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
				String downloadFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
				response.setHeader("Content-disposition", "attachment;filename=" + downloadFileName);
			} else {
				response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
			}
			// 判断参数异步情况
			if (headNames == null || headNames.isEmpty()) {
				return;
			}
			if (fieldNames == null || fieldNames.isEmpty()) {
				return;
			}
			if (datList == null) {
				datList = Collections.EMPTY_LIST;
			}
			// 创建文件
			XSSFWorkbook wb = new XSSFWorkbook();
			XSSFSheet sheet = wb.createSheet(sheetFileName);

			// 合并单元格
			Row newrow = sheet.createRow(0);
			// Cell cell = newrow.createCell(0);
			newrow.createCell(0).setCellValue(titleNames);
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 5, 0));

			// 设置行高
			newrow.setHeight((short) 1500);

			if (headNames != null && !headNames.isEmpty()) {
				// 先制作表头
				Row row = sheet.createRow(1);
				for (int i = 0; i < headNames.size(); i++) {
					String title = headNames.get(i);
					sheet.setColumnWidth(i, title.getBytes().length * 2 * 256);
					row.createCell(headNames.indexOf(title)).setCellValue(title);
				}
			}

			if (null != datList && datList.size() > 0) {
				// 将数据据行写入excel
				for (Object dat : datList) {
					Row row = sheet.createRow(datList.indexOf(dat) + 2);
					for (String field : fieldNames) {
						Object value = probe.getObject(dat, field);
						String valueStr = "";
						if (value != null) {
							valueStr = value.toString();
						}

						row.createCell(fieldNames.indexOf(field)).setCellValue(valueStr);
					}
				}
			}

			// 返回请求的注，直接在浏览器中弹出窗口下载excel
			wb.write(response.getOutputStream());
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
